package com.coocaa.typhoon.api.v1.userfile.provider;

import cn.hutool.core.io.file.FileNameUtil;
import com.coocaa.cirrus.common.third.filestore.config.TosProperties;
import com.coocaa.typhoon.api.third.volcengine.service.TOSService;
import com.coocaa.typhoon.api.v1.userfile.constant.FileSceneConstant;
import com.coocaa.typhoon.api.v1.userfile.model.UploadTmpResult;
import com.coocaa.typhoon.api.v1.userfile.util.TosFinalUrlUtil;
import com.coocaa.typhoon.api.v1.userfile.util.TosUploadFilePathUtil;
import com.drew.imaging.FileType;
import net.coobird.thumbnailator.Thumbnails;
//import org.bytedeco.javacv.FFmpegFrameGrabber;
//import org.bytedeco.javacv.Frame;
//import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bijiahao
 * @date : 2025/9/27 16:46
 * @description
 */
@Service
public class VideoFileUploadProvider {
    /**
     * 截取第几秒
     */
    private static final int START_FRAME_SECOND = 1;
    /**
     * 输出宽（0=保持比例）
     */
    private static final int WIDTH = 1280;

    private static final Float COMPRESS_QUALITY = 0.85f;   // 图片质量 85%
    @Autowired
    private TOSService tosService;
    @Autowired
    private TosProperties tosProperties;


    public List<UploadTmpResult> splitUploadImage(UploadTmpResult uploadTmpResult) throws Exception {
        List<UploadTmpResult> res = new ArrayList<>();
        String extName = FileType.Png.getName().toLowerCase();
        String remoteUploadFilePath = TosUploadFilePathUtil.getRemoteUploadFilePathForRlsFile(tosProperties.getTosEnvDir(), uploadTmpResult.getFileName(), 1, extName, FileSceneConstant.PREVIEW);
        String videoFilePath = TosFinalUrlUtil.getFilePath(uploadTmpResult.getTosLink());
        UploadTmpResult tmpResult = tosService.videoSnapshot(videoFilePath, START_FRAME_SECOND, remoteUploadFilePath, extName);
        res.add(tmpResult);
        return res;
    }


//    public List<UploadTmpResult> splitUploadImageByFFMPEG(InputStream inputStream, UploadTmpResult uploadTmpResult) throws Exception {
//        List<UploadTmpResult> res = new ArrayList<>();
//        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputStream)) {
//            grabber.start();
//            // 跳到指定秒
//            grabber.setTimestamp(START_FRAME_SECOND * 1_000_000L); // 单位微秒
//            // 2. 确保拿到的是关键帧
//            Frame frame;
//            while ((frame = grabber.grabImage()) != null) {
//                if (frame.keyFrame) {
//                    // 关键帧标识
//                    break;
//                }
//            }
//            if (frame == null) {
////                throw new RuntimeException("未找到关键帧");
//                grabber.setTimestamp(0);
//                frame = grabber.grabImage();
//            }
//            if (frame == null) {
//                throw new RuntimeException("视频无帧可抓");
//            }
//            // 转 BufferedImage
//            Java2DFrameConverter converter = new Java2DFrameConverter();
//            BufferedImage img = converter.getBufferedImage(frame);
//            // 压缩
//            ByteArrayOutputStream imgOut = new ByteArrayOutputStream();
//            String extName = FileType.Png.getName().toLowerCase();
//            /* 3. 动态缩放：宽 > 1280 才缩，否则原尺寸 */
//            int srcW = img.getWidth();
//            double scale = srcW > WIDTH ? WIDTH * 1d / srcW : 1.0;
//            Thumbnails.of(img)
//                    .scale(scale)              // 不缩放
//                    .outputQuality(COMPRESS_QUALITY)
//                    .outputFormat(extName)
//                    .toOutputStream(imgOut);
//            String remoteUploadFilePath = TosUploadFilePathUtil.getRemoteUploadFilePathForRlsFile(tosProperties.getTosEnvDir(), uploadTmpResult.getFileName(), 1, extName, FileSceneConstant.PREVIEW);
//            tosService.uploadFile(imgOut, remoteUploadFilePath);
//            UploadTmpResult tmpResult = UploadTmpResult.builder()
//                    .fileExtName(extName.toUpperCase())
//                    .fileName(FileNameUtil.getName(remoteUploadFilePath))
//                    .tosLink(TosFinalUrlUtil.getTosLink(tosProperties.getTosBucketName(), remoteUploadFilePath))
//                    .url(TosFinalUrlUtil.getHttpUrl(tosProperties.getTosUrlPrefix(), remoteUploadFilePath))
//                    .build();
//            res.add(tmpResult);
//            grabber.stop();
//        }
//
//        return res;
//    }


    private static BufferedImage resize(BufferedImage src, int w, int h) {
        if (w == 0) w = src.getWidth() * h / src.getHeight();
        if (h == 0) h = src.getHeight() * w / src.getWidth();
        BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        dst.getGraphics().drawImage(src.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null);
        return dst;
    }
}
